package weekMatch.one_351;

import java.util.*;

public class LeeCode_04 {
    public static void main(String[] args) {
        System.out.println(survivedRobotsHealths(new int[]{3, 5, 2, 6}, new int[]{10, 10, 15, 12}, "RLRL"));
    }
    private static List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
        int n = positions.length;
        Integer[] is = new Integer[n];
        for (int i = 0; i < n; i++) {
            is[i] = i;
        }
        Arrays.sort(is, Comparator.comparingInt(o -> positions[o]));
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            if (deque.isEmpty()){
                deque.push(is[i]);
            }else {
                while (!deque.isEmpty()) {
                    Integer pre = deque.peek();
                    Integer next = is[i];
                    char d1 = directions.charAt(pre);
                    char d2 = directions.charAt(next);
                    if (d1 == 'R' && d2 == 'L') {
                        int h1 = healths[pre];
                        int h2 = healths[next];
                        if (h1 == h2){
                            healths[pre] = 0;
                            healths[next] = 0;
                            deque.pop();
                            break;
                        }else if (h1 > h2){
                            healths[pre]--;
                            healths[next] = 0;
                            break;
                        }else {
                            healths[next]--;
                            healths[pre] = 0;
                            deque.pop();
                            if (healths[next] == 0) {
                                break;
                            }
                        }
                    }else {
                        deque.push(is[i]);
                        break;
                    }
                }
            }
        }
        List<Integer> list = new ArrayList<>();
        for (int health : healths) {
            if (health != 0)
                list.add(health);
        }
        return list;
    }
}